package l1j.server;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Timestamp;

import l1j.server.server.utils.SQLUtil;

public class DatabaseOrganizer {
	public void execute() {
		System.out.print("正在清除記錄資料庫.");
		try {
			con = L1DatabaseFactory.getInstance().getConnection();
			deleteTradeLogs();
			deleteWarehouseLogs();
			deletePrivateShopLogs();
			deleteDeleteItemLogs();
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			SQLUtil.close(pstm);
			SQLUtil.close(con);
		}
		System.out.println("ok");
	}

	private Connection con;

	private PreparedStatement pstm;

	private void deleteTradeLogs() throws SQLException {
		pstm = con.prepareStatement("DELETE FROM log_trade where time < ?");
		long now = System.currentTimeMillis();
		long deadline = now - 86400 * 1000 * Config.tradeLogDay;
		pstm.setTimestamp(1, new Timestamp(deadline));
		pstm.execute();
		System.out.print(".");
	}

	private void deleteWarehouseLogs() throws SQLException {
		pstm = con.prepareStatement("DELETE FROM log_warehouse where time < ?");
		long now = System.currentTimeMillis();
		long deadline = now - 86400 * 1000 * Config.warehouseLogDay;
		pstm.setTimestamp(1, new Timestamp(deadline));
		pstm.execute();
		System.out.print(".");
	}

	private void deletePrivateShopLogs() throws SQLException {
		pstm = con
				.prepareStatement("DELETE FROM log_privateshop where time < ?");
		long now = System.currentTimeMillis();
		long deadline = now - 86400 * 1000 * Config.privateShopLogDay;
		pstm.setTimestamp(1, new Timestamp(deadline));
		pstm.execute();
		System.out.print(".");
	}

	private void deleteDeleteItemLogs() throws SQLException {
		pstm = con
				.prepareStatement("DELETE FROM log_deleteitem where time < ?");
		long now = System.currentTimeMillis();
		long deadline = now - 86400 * 1000 * Config.deleteItemLogDay;
		pstm.setTimestamp(1, new Timestamp(deadline));
		pstm.execute();
		System.out.print(".");
	}
}
